<template>
    <div class="j-tbl">
        <div class="t-header c-title-5">
            <div class="th-item f-item1 acts">
                <!-- 行为 -->
                {{ $t("message.Token.Jrecord.a") }}
                <!-- <i class="iconfont icon-sanjiaoxing sea-btn"></i> -->
            </div>
            <!-- 从 -->
            <div class="th-item f-item2">
                <span @click="onShowSearchToken('from')" v-if="!searchParam.fromAddress.show">
                    {{ $t("message.Token.Jrecord.b") }}
                    <i class="iconfont icon-sanjiaoxing sea-btn"></i></span>
                <JInput v-model="searchParam.fromAddress.txt" v-show="searchParam.fromAddress.show"
                    :placeholder="searchParam.fromAddress.placeholder" @enter="onEnterSearchFromToken(false)"
                    @clear="onClearFrom"></JInput>
            </div>
            <!-- 到 -->
            <div class="th-item f-item3">
                <span @click="onShowSearchToken('to')" v-if="!searchParam.toAddress.show">{{ $t("message.Token.Jrecord.c")
                }}<i class="iconfont icon-sanjiaoxing sea-btn"></i></span>
                <JInput v-model="searchParam.toAddress.txt" v-show="searchParam.toAddress.show"
                    :placeholder="searchParam.toAddress.placeholder" @enter="onEnterSearchToToken(false)"
                    @clear="onClearTo"></JInput>
            </div>
            <!-- Buy token -->
            <div class="th-item f-item4">
                <CoinList :disabled="isToken" :list="tokenfilterList" :cur-item="toCoin"
                    @choose="e => onChooseCoin(e, 'Buy')" v-slot="slotProps">
                    <span v-bind="slotProps.props" class="pop-down">
                        <span class="wgt-1"> {{ slotProps.item ? slotProps.item.symbol : "Amount Token"
                        }}</span>
                        <i class="iconfont icon-sanjiaoxing sea-btn" v-if="!isToken"></i>
                    </span>
                </CoinList>
            </div>
            <!-- Sell token -->
            <div class="th-item f-item5">
                <CoinList :disabled="isToken" :list="tokenfilterList" :cur-item="fromCoin"
                    @choose="e => onChooseCoin(e, 'Sell')" v-slot="slotProps">
                    <span v-bind="slotProps.props" class="pop-down">
                        {{ slotProps.item ? slotProps.item.symbol : "For Token" }}
                        <i class="iconfont icon-sanjiaoxing sea-btn" v-if="!isToken"></i>
                    </span>
                </CoinList>
            </div>
            <!-- 价值 -->
            <div class="th-item f-item6">
                <FilterList @change="onRangSearch"></FilterList>
            </div>
            <!-- 时间 -->
            <div class="th-item f-item7">
                <span class="time">{{ $t("message.Token.Jrecord.g") }}</span>
                <!-- <div class="share"></div> -->
            </div>
        </div>
        <div class="list-box c-title-4">
            <div class="a-item" v-for="item in filterList">
                <!-- 行为 -->
                <div class="th-item f-item1 acts" :class="item.action !== 'sell' ? 'win-color' : 'lose-color'">{{
                    item.action || item.method }}</div>
                <!-- 从 -->
                <div class="th-item f-item2 d-flex align-center hoverIcon">
                    <div class="icon-box ico-1">
                        <span class="iconfont ic-c"
                            :class="item.fromAddressType == 'eoa' ? 'icon-touxiang' : 'icon-icon_xinfang'"></span>
                    </div>
                    <Copy :text="item.fromAddress" :hide="true" :num="3" :isCopy="true" @search="onAutoSearchFromToken"
                        @click="tokenNavigation('fromAddress', item)"> </Copy>
                </div>
                <!-- 到 -->
                <div class="th-item f-item3 d-flex align-center hoverIcon">
                    <div class="icon-box ico-2">
                        <span class="iconfont ic-c"
                            :class="item.toAddressType == 'eoa' ? 'icon-touxiang' : 'icon-icon_xinfang'"></span>
                    </div>
                    <Copy :text="item.toAddress" :isCopy="true" :hide="true" :num="3"
                        @click="tokenNavigation('toAddress', item)" @search="onAutoSearchToToken"> </Copy>
                </div>
                <!-- Buy Token -->
                <div class="th-item d-flex f-item4">
                    <div class="flex-txt text-truncate wgt">
                        <JNumber class="wgt-1" :num="item.outAmount" :is-color="true"></JNumber>
                        <span class="wgt-2 coin-link long-txt " @click="onDetail(item, 'out')">{{ item.outSymbol
                        }}</span>
                    </div>
                </div>
                <!-- Sell Token -->
                <div class="th-item d-flex f-item5">
                    <div class="text-truncate wgt">
                        <JNumber class="wgt-1" :num="item.inAmount" :is-color="true"></JNumber>
                        <span class="wgt-2 coin-link long-txt" @click="onDetail(item, 'in')">{{ item.inSymbol }}</span>
                    </div>
                </div>
                <!-- 价值 -->
                <div class="th-item f-item6">
                    <JNumber class="wgt-1" :num="item.usd" :is-color="false" prefix="$"></JNumber>
                </div>
                <!-- 时间 -->
                <div class="th-item f-item7 justify-end" style="flex: 0.4" :title="formatTimestamp(item.time)">
                    <!-- <span class="c-timew">{{ formatTimeAgo(item.time) }}</span> -->
                    <span class="time c-timew">{{ formatTimeAgo(item.time) }}</span>
                </div>
            </div>
            <JEmpty v-if="filterList.length == 0"></JEmpty>
        </div>
        <JLoding v-if="isLoading"></JLoding>
        <v-pagination :length="page.pages" :total-visible="3" class="py-2" size="small" :model-value="page.current"
            @update:modelValue="onChangePage" v-if="filterList.length"></v-pagination>
    </div>
</template>

<script lang="ts" setup>
import { formatBigNumber, formatTimestamp, formatTimeAgo } from "@/comm/format";
import { ref, onMounted, watch, reactive, onUnmounted, computed, onBeforeMount } from "vue";
import { useActivity } from "@/stores/activity";
import { difference } from "@/comm/arrayTooler";
import JShare from "@/components/j-share/index.vue";
import JLoding from "@/components/j-loding/index.vue";
import { useRoute, useRouter } from "vue-router";
import Copy from "@/components/copy/index.vue";
import JNumber from "@/components/j-number/index.vue";
import JInput from "@/components/j-input/index.vue";
import CoinList from "@/components/coin-list/index.vue";
import JEmpty from "@/components/j-empty/index.vue";
import FilterList from "../filterList.vue";
import { IRecord } from "../record";
import { URL_TOKEN_TRANSACTIONS, URL_PERSON_TRANSACTIONS, URL_CAPITAL_TRANSACTIONS } from "@/comm/api";
import { get } from "@/comm/request";
import i18n from "@/locals";
import { useCapital } from "@/stores/capital";
import { usePerson } from "@/stores/person";
import { sleep } from "@/comm/tooler";
const activity = useActivity();
const router = useRouter();
const route = useRoute();
const desserts = ref<any[]>([]);
const capital = useCapital();
const person = usePerson();
const isLoading = ref(false);
const page = reactive({
    current: 1,
    pages: 0,
    total: 0
});

const fromCoin = ref(null as any);
const toCoin = ref(null as any);
//币种过滤列表 根据当前路由判断
const tokenfilterList = computed(() => {
    //机构
    if (props.page == "browser") {
        return capital.blockBalanceList || [];
    }
    //个人
    if (props.page == "person") {
        return person.blockBalanceList || [];
    }
    return [];
});

//Buy Sell表头选项
const onChooseCoin = (val: any, type: string) => {
    // console.log('选择的token', type, val)
    switch (type) {
        case "Buy":
            if (val) {
                toCoin.value = {
                    symbol: val.symbol,
                    contractAddress: val.contractAddress
                };
            } else toCoin.value = null;
            break;
        case "Sell":
            if (val) {
                fromCoin.value = {
                    symbol: val.symbol,
                    contractAddress: val.contractAddress
                };
            } else fromCoin.value = null;
            break;
    }
    page.current = 1;
    loadPage();
};

const onClearFrom = () => {
    searchParam.fromAddress.txt = "";
    page.current = 1;
    onEnterSearchFromToken(true);
};
const onClearPerson = () => {
    searchParam.personAddress.txt = "";
    page.current = 1;
    onEnterSearchPerson(true);
};
const onClearRelation = () => {
    searchParam.relationAddress.txt = "";
    searchParam.relationAddress.relationId = "";
    page.current = 1;
    onEnterSearchRelation(true);
};
const onClearTo = () => {
    searchParam.toAddress.txt = "";
    page.current = 1;
    onEnterSearchToToken(true);
};
const onAutoSearchFromToken = (str: string) => {
    searchParam.fromAddress.txt = str;
    searchParam.fromAddress.show = true;
    onEnterSearchFromToken(false);
};
const onAutoSearchToToken = (str: string) => {
    searchParam.toAddress.txt = str;
    searchParam.toAddress.show = true;
    onEnterSearchToToken(false);
};
const onAutoSearchToPerson = (str: string, item: any) => {
    const key = findKey(str, item)
    searchParam.personAddress.txt = str
    searchParam.personAddress.show = true;
    if (key == 'fromAddress') {
        searchParam.personAddress.type = 'from'
    }
    if (key == 'toAddress') {
        searchParam.personAddress.type = 'to'
    }
    if (key == 'relationAddress') {
        searchParam.personAddress.type = 'relation'
    }
    onEnterSearchPerson(false);
};

const onAutoSearchTorelation = (str: string, item: any) => {
    searchParam.relationAddress.txt = str;
    //如果有relationId 说明该条数据是来自机构 反之是个人
    if (item.relationId) {
        searchParam.relationAddress.relationId = item.relationId;
    } else {
        searchParam.relationAddress.relationId = "";
    }
    searchParam.relationAddress.show = true;
    onEnterSearchRelation(false);
};
const props = defineProps({
    token: String,
    method: String,
    time: Object,
    page: {
        type: String,
        default: "token"
    }
});

const actions = ref(["all", "sell", "buy", "swap"]);

watch(
    () => props.time?.value,
    () => {
        loadPage();
    }
);

const onJump = (item: any) => {
    console.log("点击跳转外部", item);
    if (item?.transactionHash) {
        window.open("https://etherscan.io/tx/" + item.transactionHash);
    }
    if (item?.txnHash) {
        window.open("https://etherscan.io/tx/" + item.txnHash);
    }
};
const isToken = computed(() => {
    return props.page == "token";
});
const isBrowser = computed(() => {
    return props.page == "browser";
});
const isPerson = computed(() => {
    return props.page == "person";
});
const routerId = computed(() => {
    return route.params.id;
});
//个人详情中 只显示一个地址 只显示非当前个人地址的
const fliterPersonAddress = (item: any) => {
    if (item.fromAddress == route.params.id) {
        return item.toAddress;
    } else if (item.toAddress == route.params.id) {
        return item.fromAddress;
    } else {
        return item.relationAddress || item.toAddress || item.fromAddress
    }
};
const curAction = ref(actions.value[0]);

const filterList = computed(() => {
    if (curAction.value == "all") {
        return list.value;
    }
    return list.value.filter((i: any) => i.action == curAction.value);
});

const searchParam = reactive({
    usd: {
        txt: "",
        show: false,
        // placeholder: "搜索"
        placeholder: i18n.global.t("message.Token.Jrecord.h")
    },
    personAddress: {
        txt: "",
        show: false,
        // placeholder: "搜索",
        placeholder: i18n.global.t("message.Token.Jrecord.h"),
        type: ""
    },
    fromAddress: {
        txt: "",
        show: false,
        // placeholder: "搜索",
        placeholder: i18n.global.t("message.Token.Jrecord.h")
        // type: ""
    },
    relationAddress: {
        txt: "",
        relationId: "",
        show: false,
        placeholder: i18n.global.t("message.Token.Jrecord.h")
    },
    toAddress: {
        txt: "",
        show: false,
        // placeholder: "搜索",
        placeholder: i18n.global.t("message.Token.Jrecord.h")
        // type: ""
    },

});

const onRangSearch = (n: number) => {
    searchParam.usd.txt = n + "";
    loadPage();
};

const onShowSearchUSD = () => {
    searchParam.usd.show = true;
    window.addEventListener("mousedown", onHideSearch);
};

const onShowSearchToken = (type: string) => {
    if (type == "to") {
        searchParam.toAddress.show = true;
    } else {
        searchParam.fromAddress.show = true;
    }
    window.addEventListener("mousedown", onHideSearch);
};

onUnmounted(() => {
    window.removeEventListener("mousedown", onHideSearch);
});

const onHideSearch = (e: any) => {
    console.log(e);
    const list = e.target.classList;
    if (list.contains("j-input-txt")) {
        console.log("click input");
    } else if (list.contains("j-input-close")) {
        console.log("click close");
    } else {
        searchParam.usd.show = false;
        searchParam.fromAddress.show = false;
        searchParam.toAddress.show = false;
    }
};

const onEnterSearchUSD = (val: boolean) => {
    console.log(searchParam.usd.txt);
    if (val) {
        searchParam.usd.show = false;
    }
    window.removeEventListener("mousedown", onHideSearch);
    loadPage();
};

const onEnterSearchFromToken = (val: boolean) => {
    if (val) {
        searchParam.fromAddress.show = false;
    }
    window.removeEventListener("mousedown", onHideSearch);
    page.current = 1;
    loadPage();
};
const onEnterSearchPerson = (val: boolean) => {
    if (val) {
        searchParam.personAddress.show = false;
    }
    window.removeEventListener("mousedown", onHideSearch);
    page.current = 1;
    loadPage();
};
const onEnterSearchToToken = (val: boolean) => {
    if (val) {
        searchParam.toAddress.show = false;
    }

    window.removeEventListener("mousedown", onHideSearch);
    page.current = 1;
    loadPage();
};
const onEnterSearchRelation = (val: boolean) => {
    if (val) {
        searchParam.relationAddress.show = false;
    }
    window.removeEventListener("mousedown", onHideSearch);
    page.current = 1;
    loadPage();
};

const onFilter = (type: string) => {
    console.log(type);
    curAction.value = type;
};

const list = ref<IRecord[]>([]);

onMounted(() => {
    console.log("====jsz swap");
    loadPage();
});
const findKey = (targetValue: any, item: any) => {
    let key = ''
    for (let i in item) {
        if (item[i] == targetValue) {
            key = i
        }
    }
    return key
}


const onChangePage = (param: any) => {
    console.log(param, "0000");
    page.current = param;
    loadPage();
};

const loadPage = async () => {
    isLoading.value = true;
    let param: any = {
        method: props.method,
        current: page.current,
        size: 10
    };
    let api = "";
    if (searchParam.usd.txt) {
        param.usd = searchParam.usd.txt;
    }
    if (searchParam.fromAddress.txt) {
        param.fromAddress = searchParam.fromAddress.txt;
    }
    if (searchParam.toAddress.txt) {
        param.toAddress = searchParam.toAddress.txt;
    }
    if (props.page == "token") {
        api = URL_TOKEN_TRANSACTIONS;
        param.tokenAddress = props.token;
    }
    param.type = props.time?.value;
    console.log("swap param ===============> !!!!!!!!!!!!!!", param);
    let res: any = await get(api, param);
    list.value = res.data?.records || [];
    page.pages = res.data?.pages || 0;
    isLoading.value = false;
    console.log("method===============>", res.data?.records);
};

const onDetail = (coin: any, type: string) => {
    let ct = type == "in" ? coin.inTokenAddress : coin.outTokenAddress;
    console.log("跳转到币对详情", ct);
    // router.push({ name: 'token', params: { id: ct } });
    window.open("/token/" + ct);
};
const tokenNavigation = (str: string, event: any) => {
    const personURL = "/address/";
    const browserURL = "/entity/";
    if (str == 'toAddress') {
        if (event.toAddressType == 'eoa') {
            window.open(`${personURL}${event.toAddress}`)
        }
        if (event.toAddressType == 'cex' || event.toAddressType == 'fund') {
            window.open(`${browserURL}${event.toAddress}`)
        }
    }
    if (str == 'fromAddress') {
        if (event.fromAddressType == 'eoa') {
            window.open(`${personURL}${event.fromAddress}`)
        }
        if (event.fromAddressType == 'cex' || event.fromAddressType == 'fund') {
            window.open(`${browserURL}${event.fromAddress}`)
        }
    }
};

defineExpose({
    loadPage
});
</script>

<style lang="less" scoped>
@import url("./tokenSwap.less");
</style>
